package collaborynth.apod;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

public class RSSHandler {
	
	private List<RSSObject> rssobjects;
	
	RSSHandler(){
		
	}
	
	public List<RSSObject> getResults(String url){
		try{
        	URL urlc = new URL(url);
        	//Log.d("Url_Query", urlc.getQuery());
        	XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        	factory.setNamespaceAware(true);
        	XmlPullParser xpp = factory.newPullParser();
        	xpp.setInput(urlc.openStream(), null);
        	InputStream input = urlc.openStream();
        	StringBuffer out = new StringBuffer();
            byte[] b = new byte[4096];
            for (int n; (n = input.read(b)) != -1;) {
                out.append(new String(b, 0, n));
            }
            //Log.d("Raw", out.toString());
        	int eventType = xpp.getEventType();
        	int inItem = 0;
        	RSSObject currentitem = null;
        	while (eventType != XmlPullParser.END_DOCUMENT) {
        		
        		String name = "";
        		String link = "";
        		switch(eventType){
        			case XmlPullParser.START_DOCUMENT:
        				rssobjects = new ArrayList<RSSObject>();
        				break;
        			case XmlPullParser.START_TAG:
        				name = xpp.getName();
        				if(name.equalsIgnoreCase("item")){
        					currentitem = new RSSObject();
        				} else if(currentitem != null){
        					if(name.equalsIgnoreCase("link")){
        						link = xpp.nextText();
        						currentitem.setPageURL(link);
        					}
        				}
        				break;
        			case XmlPullParser.END_TAG:
        				name = xpp.getName();
        				if(name.equalsIgnoreCase("item")){
        					rssobjects.add(currentitem);

        				}
        				break;
        		}
        		eventType = xpp.next();
        	}
        }catch(MalformedURLException e){
        	
        }catch(XmlPullParserException e){
        		Log.e("XmlParserError", e.getMessage());
        }catch(IOException e){
        	
        }
       
        return rssobjects;
	}
}
